<?php

namespace app\command;

use app\admin\controller\DiscountCodes;
use app\model\DistrictCodesModel;
use app\model\RedisModel;
use app\model\UserUseDiscountCodeLogModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class UpdateDiscountCodes extends Command
{

    public $cacheKey="discount:codes:";

    protected function configure()
    {
        $this->setName('更新优惠码')
            ->setDescription('批量处理更新优惠码');
    }

    protected function execute(Input $input, Output $output)
    {
        // 执行你的脚本任务代码
        $where = [];
        $where[] = ["is_delete", "=", "0"];
        $where[] = ["use_status", "IN", [0, 1, 2]];
        $list = Db::name("discount_codes")->where($where)->select();
        $userUseDiscountCodeLogModel = new UserUseDiscountCodeLogModel();
        if ($list) {
            $list = $list->toArray();
            var_dump($list);
            foreach ($list as $one) {
                $one['have_used'] = $userUseDiscountCodeLogModel->where(["code"=> $one["code"], "is_delete"=>0])->count();

                if (!empty($one["end_time"]) && strtotime($one["end_time"]) < time()) {
                    Db::name("discount_codes")->where(["code" => $one["code"]])->save(["use_status" => -1, "use_msg" => "已过期"]);
                } elseif ($one["max_uses"] > 0) {
                    if ($one['have_used'] >= $one["max_uses"]) {
                        Db::name("discount_codes")->where(["code" => $one["code"]])->save(["use_status" => 2, "use_msg" => "已使用"]);
                    } else if($one['have_used'] > 0 ){
                        Db::name("discount_codes")->where(["code" => $one["code"]])->save(["use_status" => 1, "use_msg" => "正在使用"]);
                    }else {
                        Db::name("discount_codes")->where(["code" => $one["code"]])->save(["use_status" => 0, "use_msg" => "未使用"]);
                    }
                }elseif ($one["max_uses"] == 0) {
                    if($one['have_used'] > 0 ){
                        Db::name("discount_codes")->where(["code" => $one["code"]])->save(["use_status" => 1, "use_msg" => "正在使用"]);
                    }else {
                        Db::name("discount_codes")->where(["code" => $one["code"]])->save(["use_status" => 0, "use_msg" => "未使用"]);
                    }
                }

                $redisModel = new RedisModel();

                $redisModel->delete($this->cacheKey.$one["code"]);
            }
        }
    }
}